import Taro from "@tarojs/taro";

// 路由
const BASEURL =
  process.env.NODE_ENV === "development"
    ? "https://djc.dgruiyikeji.com/api"
    : "https://djc.dgruiyikeji.com/api"; // http://192.168.0.221:20145/api

// 获取本地存储的 Cookie
import store from "@/redux/index";
import { changeMember_id } from "@/redux/userSlice";

export default function (
  url: string, // 请求地址
  data: object,  // 请求体
  headers: any, // 请求头
  method: keyof Taro.request.Method | undefined // 请求方法 默认POST
) {
  return new Promise<any>((resolve, reject) => {
    // 导入模块 2.使用方法
    const myCookie = Taro.getStorageSync("cookie");
    // console.log(myCookie, " myCookie");
    Taro.request({
      url: BASEURL + url,
      method: method ? method : "POST",
      data: data,
      header: {
        ...headers,
        Cookie: myCookie ? `${myCookie.toString()}` : "1123",
      },
      // timeout: 8000,
      // responseType: "json",
      success: (res) => {
        console.log(res.header, "res"); // 响应头
        const cookie = res.header["set-cookie"] || res.header["Set-Cookie"] || "";
        // 存储
        cookie && Taro.setStorageSync("cookie", cookie);


        // 统一处理code = 0
        if (res.data.code == 0) {
          resolve(res.data);
        } else if (res.data.code == 2006) {
          resolve(res.data);
        } else if (res.data.code == 2001) {
          store.dispatch(changeMember_id(""));
          const pages = Taro.getCurrentPages();
          console.log(pages, "pages");
          const str = pages[pages.length - 1].route != "pages/home/index";
          const str1 = pages[pages.length - 1].route != "pages/user/index";
          if (str && str1) {
            // Toast.show({ content: res.data.msg, icon: "fail" });
            Taro.showToast({
              title: res.data.msg || "错误",
              icon: "error",
              duration: 2000,
            });
            setTimeout(() => {
              Taro.reLaunch({
                url: "/pages/home/index",
              });
            }, 500);
          } else {
            Taro.showToast({
              title: res.data.msg || "错误",
              icon: "error",
              duration: 2000,
            });
          }
          // reject(res.data);
          resolve(res.data);
        } else {
          resolve(res.data);
          // reject(res.data);
        }
      },
      fail: (err) => {
        // if (err.statusCode && err.statusCode !== 200) {
        //   console.log("跳转到登录页");
        // }
        reject(err);
      },
    });
  });
}
